package com.example.project44

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.core.view.children
import androidx.gridlayout.widget.GridLayout
import com.example.cardgame.model.CardMatchingGame

class GameActivity : ComponentActivity(), View.OnClickListener {
    lateinit var game: CardMatchingGame
    val cardButtons = mutableListOf<Button>()
    @SuppressLint("MissingInflatedId")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_game)

        val gridLayout = findViewById<GridLayout>(R.id.gridLayout)
        for (v in gridLayout.children) {
            if (v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }
        game = CardMatchingGame(cardButtons.count())
        updateUI()

        val reset = findViewById<Button>(R.id.button_reset)
        reset.setOnClickListener {
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }
        val btnBack = findViewById<Button>(R.id.button_back)
        btnBack.setOnClickListener {
            finish()
        }
    }

    fun updateUI() {
        for (button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(Color.WHITE)
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.photo)
            }
        }
        val score = findViewById<TextView>(R.id.textView)
        score.text = String.format("%s%d", getString(R.string.text), game.score)

        val btnBack = findViewById<Button>(R.id.button_back)
        btnBack.setOnClickListener {
            val intent = Intent().apply {
                putExtra("score", game.score)
            }
            setResult(RESULT_OK, intent)
            finish()
        }
    }
    private fun isGameOver(): Boolean {
        for (i in 0 until cardButtons.count()) {
            if (!game.cardAtIndex(i).isMatched) {
                return false
            }
        }
        return true
    }

    override fun onClick(v: View?) {
        if (v is Button) {
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }
}